import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geomancy/enums/index.dart';
import 'package:geomancy/providers/gallery_provider.dart';
import 'package:geomancy/providers/system_provider.dart';
import 'package:geomancy/styles/index.dart';
import 'package:geomancy/widgets/common_modal_rectangle.dart';
import 'package:geomancy/widgets/common_photo_permission_btn_widget.dart';
import 'package:geomancy/widgets/gallery_util/components/assets_entity_widget.dart';
import 'package:geomancy/widgets/gallery_util/components/photograph_widget.dart';
import 'package:geomancy/widgets/gallery_util/index.dart';
import 'package:photo_manager/photo_manager.dart';
import 'package:provider/provider.dart';


class GalleryWidget extends StatefulWidget {
  ///相册使用场景
  final GalleryScene scene;
  ///显示资源类型(default = common)
  ///此应用中只有当上传、修改头像以及创建入口时候传入 type = image
  final RequestType requestType;
  ///可以选中几个相册资源(default = 9)
  final int maxCount;
  const GalleryWidget({super.key, this.scene = GalleryScene.common, this.maxCount = 9, this.requestType = RequestType.common});

  @override
  State<GalleryWidget> createState() => _GalleryWidgetState();
}
class _GalleryWidgetState extends State<GalleryWidget> {
  ///接收相册数据流
  StreamSubscription<List<AssetEntity>>? _subscription;
  ///相册所有资源列表
  List<AssetEntity> assetsList = [];
  ///展示在界面的资源
  List<AssetEntity> assetsShowList = [];
  int tmpSelectedGalleryLength = 0;
  ///是否具有相册权限
  bool? hasGalleryAuth;


  @override
  void initState() {
    super.initState();
    tmpSelectedGalleryLength = context.read<GalleryProvider>().getTmpSelectedList.length;
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      context.read<GalleryProvider>().setMaxLength = widget.maxCount;
      context.read<GalleryProvider>().setGalleryScene = widget.scene;
      // if (widget.scene == GalleryScene.cover) {
      //   context.read<GalleryProvider>().setCropAspectRatio = Constant.ROOMCOVERRATIO;
      // }
      ///加个延时，防止modal在弹起过程中开始渲染，导致卡顿
      Future.delayed(const Duration(milliseconds: 200), getPermission);
    });
  }

  @override
  void dispose() {
    _subscription?.cancel();
    super.dispose();
  }

  getPermission() {
    GalleryUtils.getPermission(
      context: context,
      success: () {
        getAssetEntityListByType(widget.requestType);
        setState(() {
          hasGalleryAuth = true;
        });
        GalleryUtils.addListener(galleryChangeCallback);
      },
      failed: () {
        setState(() {
          hasGalleryAuth = false;
        });
        context.read<GalleryProvider>().setAllGalleryMediaList = [];
      }
    );
  }

  Future galleryChangeCallback(MethodCall value) async {
    if (value.method == 'change') {
      if (value.arguments['update'].isNotEmpty) {
        final List<AssetEntity> assetList = [];
        for (int i = 0; i < value.arguments['update'].length; i++) {
          final asset = await AssetEntity.fromId(value.arguments['update'][i]['id']);
          if (asset != null) {
            assetList.add(asset);
          }
        }
        setState(() {
          assetsShowList.insertAll(0, assetList);
        });
      }
    }
  }

  ///获取相册图片列表
  Future getAssetEntityListByType(RequestType type) async {
    _subscription = GalleryUtils.getAssetEntityListByType(context, type).listen((entities) {
      assetsList.addAll(entities);
      setState(() {
        assetsShowList.addAll(entities);
      });
    });
  }


  @override
  Widget build(BuildContext context) {
    final topSafeHeight = context.read<SystemProvider>().getTopSafeHeight;
    final bottomSafeHeight = MediaQuery.of(context).padding.bottom;
    final screenHeight = MediaQuery.of(context).size.height;
    final containerH = screenHeight - topSafeHeight;
    final tmpSelectedList = context.watch<GalleryProvider>().getTmpSelectedList;

    return Container(
      width: double.infinity,
      height: containerH,
      color: ColorStyle.themeLightColor,
      child: SizedBox(
        width: double.infinity,
        child: Column(
          children: [
            ///顶部装饰条
            const CommonModalRectangle(),
            ///相册资源列表
            if (hasGalleryAuth == true)
              Expanded(child: GridView.builder(
                cacheExtent: 2000,
                itemCount: assetsShowList.length + 1,
                physics: const ClampingScrollPhysics(),
                padding: EdgeInsets.only(left: 60.w, right: 60.w, bottom: tmpSelectedList.isEmpty ? bottomSafeHeight : 142.w + bottomSafeHeight + 6.w),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3,
                  mainAxisSpacing: 15.w,
                  crossAxisSpacing: 15.w,
                ),
                itemBuilder: (context, index) {
                  if (index == 0) {
                    return const GalleryPhotographWidget();
                  } else {
                    final realIndex = index - 1;
                    final entity = assetsShowList[realIndex];
                    final currentIndex = tmpSelectedList.indexOf(entity);
                    return AssetsEntityWidget(
                      entity: entity,
                      size: Size(200.w, 200.w),
                      radius: 30.w,
                      isChecked: currentIndex > -1,
                      currentIndex: currentIndex > -1 ? currentIndex + 1 : null,
                    );
                  }
                }
              ))
            else if (hasGalleryAuth == false)
              const Expanded(child: SizedBox(
                width: double.infinity,
                child: CommonPhotoPermissionBtnWidget(),
              ))
          ],
        ),
      ),
    );
  }
}
